<template>
  <el-dialog
    draggable
    :title="title"
    :close-on-click-modal="false"
    v-model="open"
    width="70%"
    append-to-body
  >
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
      class="form-search"
    >
      <template v-for="(el, index) in search" :key="index">
        <SearchTool
          v-if="el.type == 'searchTool'"
          :layout="false"
          :code="el.code || searchToolConfig.code"
          v-model:factory="
            queryParams[
              el.code && el.code.factory
                ? el.code.factory
                : searchToolConfig.code.factory
            ]
          "
          v-model:workshop="
            queryParams[
              el.code && el.code.workshop
                ? el.code.workshop
                : searchToolConfig.code.workshop
            ]
          "
          v-model:line="
            queryParams[
              el.code && el.code.line
                ? el.code.line
                : searchToolConfig.code.line
            ]
          "
          v-model:section="
            queryParams[
              el.code && el.code.section
                ? el.code.section
                : searchToolConfig.code.section
            ]
          "
          :showFactory="!!el.showFactory"
          :showWorkshop="!!el.showWorkshop"
          :showLine="!!el.showLine"
          :showSection="!!el.showSection"
        ></SearchTool>
        <el-form-item
          v-else-if="el.prop == 'factory'"
          label="工厂"
          :prop="el.prop"
        >
          <DeptSelect
            v-model="queryParams[el.prop]"
            v-model:name="queryParams.factoryName"
            key="factory"
            placeholder="请选择工厂"
            type="factory"
          ></DeptSelect>
        </el-form-item>
        <el-form-item v-else :label="el.label" :prop="el.prop">
          <el-input
            v-model="queryParams[el.prop]"
            :placeholder="el.placeholder"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      </template>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <div
      style="display: flex; gap: 0.5rem; flex-wrap: wrap; margin-bottom: 10px"
    >
      <el-tag
        v-for="(tag, index) in selectData"
        :key="index"
        @close="handleClose(tag)"
        closable
      >
        {{ tag[labelKey] }}
      </el-tag>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      ref="tableRef"
      border
      maxHeight="500px"
      :row-key="rowKey"
      :highlight-current-row="!multiple"
      @current-change="handleCurrentChange"
      @select="handleSelectionChange"
    >
      <el-table-column
        v-if="multiple"
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        v-for="(el, index) in columns"
        :label="el.label"
        :key="index"
        :align="el.align"
        :prop="el.prop"
        :show-overflow-tooltip="true"
      />
    </el-table>
    <pagination
      v-if="showPagination"
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="MatDialog">
import { computed, nextTick, toRefs } from "vue";
const { proxy } = getCurrentInstance();

const open = defineModel("show");
const modelValue = defineModel();
const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  multiple: {
    type: Boolean,
    default: true,
  },
  search: {
    type: Array,
    default: () => [],
  },
  columns: {
    type: Array,
    default: () => [],
  },
  rowKey: {
    type: String,
    default: "id",
  },
  labelKey: {
    type: String,
    default: "name",
  },
  api: null,
  dataCallback: null,
  initParam: {},
  showPagination: {
    type: Boolean,
    default: true,
  },
});
const {
  searchParams,
  title,
  multiple,
  columns,
  rowKey,
  labelKey,
  api,
  initParam,
} = toRefs(props);
const loading = ref(true);
const showSearch = ref(true);
const tableData = ref([]);
const ids = ref([]);
const single = ref(true);
const selectData = ref([]);
const tableRef = ref("tableRef");
const total = ref(0);
const currentRow = ref();
const queryRef = ref("queryRef");
const settingSelect = ref(false);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
});

const searchToolConfig = ref({
  code: {
    factory: "factory",
    workshop: "workshopSectionCode",
    line: "productionLineCode",
    section: "processSegmentCode",
  },
});

const { queryParams } = toRefs(data);

const emit = defineEmits(["change"]);

const selectedIds = computed(() => {
  let ids = [];
  selectData.value.forEach((item) => ids.push(item[rowKey.value]));
  return ids;
});
const currentPageIds = computed(() => {
  let ids = [];
  tableData.value.forEach((item) => ids.push(item[rowKey.value]));
  return ids;
});

function otherPageData(dataList) {
  return dataList.filter(
    (el) => !currentPageIds.value.includes(el[rowKey.value])
  );
}

watch(
  () => open.value,
  (newValue) => {
    if (newValue) {
      if (multiple.value) {
        selectData.value = modelValue.value;
      } else {
        currentRow.value = modelValue.value;
      }
      getList();
    }
  }
);

/** 查询字典类型列表 */
function getList() {
  loading.value = true;
  const params = {
    ...initParam.value,
    ...queryParams.value,
  };
  api
    .value(params)
    .then((response) => {
      if (props.dataCallback) {
        const data = props.dataCallback(response);
        tableData.value = data;
        total.value = response.total;
      } else {
        tableData.value = response.rows;
        total.value = response.total;
      }
      loading.value = false;
      nextTick(() => {
        setTableSelect(true);
      });
    })
    .catch(() => {
      loading.value = false;
    });
}

function setTableSelect(type) {
  let selects = [];
  if (multiple.value) {
    if (selectData.value) {
      selects = selectData.value.map((item) => item[rowKey.value]);
    }
  } else {
    if (currentRow.value) {
      selects = [currentRow.value[rowKey.value]];
    }
  }

  tableData.value.forEach((el, index) => {
    settingSelect.value = true;
    if (selects.includes(el[rowKey.value])) {
      setCurrent(index, type);
    }
  });
  nextTick(() => {
    settingSelect.value = false;
  });
}

const setCurrent = (index, type) => {
  if (multiple.value) {
    tableRef.value.toggleRowSelection(tableData.value[index], type);
  } else {
    tableRef.value.setCurrentRow(tableData.value[index]);
  }
};

const handleCurrentChange = (val) => {
  currentRow.value = val;
};

const handleClose = (tag) => {
  selectData.value = selectData.value.filter(
    (el) => el[rowKey.value] !== tag[rowKey.value]
  );
  let index = tableData.value.findIndex(
    (el) => el[rowKey.value] === tag[rowKey.value]
  );
  if (index !== -1) {
    tableRef.value.toggleRowSelection(tableData.value[index], false);
  }
};

/** 取消按钮 */
function cancel() {
  open.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryRef.value.resetFields();
  if (queryParams.value.factoryName) {
    queryParams.value.factoryName = "";
  }
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection, row) {
  if (!settingSelect.value) {
    let otherData = otherPageData(selectData.value);
    selectData.value = otherData.concat(selection);
  }
}

function submitForm() {
  if (multiple.value) {
    if (!selectData.value.length) {
      proxy.$modal.msgError("请选择数据");
      return;
    }
    modelValue.value = selectData.value;
    open.value = false;
    emit("change", selectData.value);
  } else {
    if (!currentRow.value) {
      proxy.$modal.msgError("请选择数据");
      return;
    }
    modelValue.value = currentRow.value;
    open.value = false;
    emit("change", currentRow.value);
  }
}

defineExpose({
  selectedIds,
});
</script>

<style lang="scss" scoped></style>
